package br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;

import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.ProgramDAO;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.entity.Program;

public class JPAProgramDAO implements ProgramDAO {

	private EntityManager emf;

	public JPAProgramDAO(EntityManager emf) {
		this.emf = emf;
	}

	@Override
	public void create(Program program) {
		try {
			emf.getTransaction().begin();
			emf.persist(program);
			emf.getTransaction().commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public Program loadByCRID(String crid) {
		return emf.find(Program.class, crid);
	}

	@Override
	public void delete(String crid) {
		Program program = loadByCRID(crid);
		if (program == null)
			return;
		try {
			emf.getTransaction().begin();
			emf.remove(program);
			emf.getTransaction().commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Program> loadAll() {
		return emf.createQuery("select p from Program p").getResultList();
	}

}
